#include "main.h"

#define HC595_SEG_NUM 4

#define SEG_DIG1 P33
#define SEG_DIG2 P34
#define SEG_DIG3 P35
#define SEG_DIG4 P36

#define SET_SEG_OUT(x) \
P_SW2 = 0x80;\
P1PU = x&Bin(11111100);\
P5PU = x<<4;\
P_SW2 = 0x00

uchar code Seg_map[10] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; //0~9显示代码
uint8_t seg_buf[HC595_SEG_NUM];

void Timer0Init(void)		//5毫秒@32MHz
{
	AUXR &= 0x7F;		//定时器时钟12T模式
	TMOD &= 0xF0;		//设置定时器模式
	TL0 = 0xEB;		//设置定时初始值
	TH0 = 0xCB;		//设置定时初始值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
    
    ET0 = 1;
}

void seg_init()
{
    P1M0 &= ~Bin(11111100);
    P1M1 |= Bin(11111100);
    P5M0 &= ~Bin(00110000);
    P5M1 |= Bin(00110000);
    
    P3M0 |= Bin(01111000);
    P3M1 |= Bin(01111000);
    
    P1 = 0;
    P5 = 0;
    SEG_DIG1 = 1;
    SEG_DIG2 = 1;
    SEG_DIG3 = 1;
    SEG_DIG4 = 1;
    
    Timer0Init();
    
    seg_buf[0] = 0x3f;
    seg_buf[1] = 0xff;
    seg_buf[2] = 0x03;
    seg_buf[3] = 0xff;
}

void TM0_Isr() interrupt 1
{
    static uint8_t seg_num=0;
    
    switch(seg_num)
    {
    case 0:
        SEG_DIG4 = 1;
        SET_SEG_OUT(seg_buf[0]);
        seg_num = 1;
        SEG_DIG1 = 0;
    break;
    case 1:
        SEG_DIG1 = 1;
        SET_SEG_OUT(seg_buf[1]);
        seg_num = 2;
        SEG_DIG2 = 0;
    break;
    case 2:
        SEG_DIG2 = 1;
        SET_SEG_OUT(seg_buf[2]);
        seg_num = 3;
        SEG_DIG3 = 0;
    break;
    case 3:
        SEG_DIG3 = 1;
        SET_SEG_OUT(seg_buf[3]);
        seg_num = 0;
        SEG_DIG4 = 0;
    break;
    }
    
    timer += 5;
}

